const alioss = require('ali-oss');
const path = require('path');

module.exports = class oss extends alioss {
    constructor(connStr, ctx, opts) {
        if (!opts) {
            opts = ctx;
            ctx = undefined;
        }
        super(connStr, ctx);
        if (!opts)
            opts = {};
        this.opts = opts;
    }

    /**
     * 验证录屏是否存在
     * @param route
     * @returns {Promise<boolean|Runtime.RemoteObject>}
     */
    async exists(route) {
        if (!route) {
            return false;
        }
        return super.list(
            {
                prefix: `${this.opts.prefix}${route}`,
                'max-keys': 1
            }).then(this.resStatus).then(function(rts) {
            return rts.objects;
        });
    }

    /**
     * 上传文件
     * @param filename
     * @param args
     * @return {Promise<T>}
     */
    async putStream(filename, ...args) {
        return super.putStream(`${this.opts.prefix}${filename}`, ...args).then(this.resStatus);
    }

    /**
     * 验证文件信息
     * @param filename
     * @param args
     * @returns {Promise<PromiseLike<*> | Promise<*>>}
     */
    async head(filename, ...args) {
        return super.head(`${this.opts.prefix}${filename}`, ...args).then(this.resStatus)
    }

    /**
     * windows下转换文件路径
     * @param filepath
     * @returns {string}
     */
    static parsePath(filepath) {
        return path.sep === '\\' ? filepath.split(path.sep).join('/') : filepath;
    }

    resStatus(rts) {
        if (rts.res.status !== 200 || rts.res.statusMessage !== 'OK') {
            return Promise.reject(rts);
        }
        return rts;
    }
};

